import React from 'react';
import { Text, View, ScrollView, Alert, StyleSheet, StatusBar,ActivityIndicator } from 'react-native';
import { HStack, VStack, Fab, Input, Select ,Pressable} from "native-base";
import Ionicons from 'react-native-vector-icons/Ionicons';
import BasicTable from '../../components/Table/RNTable';
import FormDatePicker from '../../components/Form/FormDatePicker';
import { fetch_post } from '../../http/http';

function FkdDetails({navigation}){

  function createData(num){
    let array:any[] = []
    for(let i=1; i<=num; i++){
      let item = ['uid'+i,'2024-03-20','江苏南京'+i, '邻里纠纷']
      array.push(item);
    }
    return array;
  }


  let [state,setState] = React.useState({
    // tableHead: ['uid', 'time', 'address', 'type'],
    // tableData: createData(59),
    tableHead: [],
    tableData: [],
  })
  let [loadingstate,setLoadingstate] = React.useState(true);

  React.useEffect(()=> {
    // 请求数据，加载页面
    init();
  },[])

  async function init(){
    const title = await getList();
    let array: any[] = [];
    Object.keys(title[0]).forEach(key => {
      array.push(key);
    })

    setState({
      tableHead: array,
      tableData: createData(59),
    })
    setLoadingstate(false);
  }

  async function getList(){
    try{
      let titleRes = await fetch("https://jsonplaceholder.typicode.com/posts")
      return await titleRes.json();
    }catch(error){
      console.log("await 报错", error);
    }
  }


  function fliter(){
    console.log('字段为',filterFiled,'\n规则为',filterRule,'\n范围为',inputvalueRange1,inputvalueRange2,'\n查询值为',inputvalue)

    if(filterFiled=="") return Alert.alert(`请输入筛选字段`)
    if(filterRule=="") return Alert.alert(`请输入筛选规则`)
    console.log('继续执行')

    const rule = {
      "is": "=",
      "like":"like",
      "in": "in",
    };

    let sqlcmd = 'select * from table where ' + filterFiled + " " + rule[filterRule] + " " + inputvalue;
    console.log(sqlcmd)

    setState({
      tableHead: ['uid', 'time', 'address', 'type'],
      tableData: [
        ['uidxxx','2024-03-20','江苏南京', '邻里纠纷'],
        ['uidyyy','2024-04-02','江苏无锡', '打架斗殴'],
      ]
    });
  }

  let [filterFiled, setFilterFiled] = React.useState('');
  let [filterRule, setFliterRule] = React.useState('');
  let [inputvalueRange1, setInputvalueRange1] = React.useState(new Date());
  let [inputvalueRange2, setInputvalueRange2] = React.useState(new Date());
  let [inputvalue, setInputvalue] = React.useState('');

  let tableref = React.useRef(null)

  return (
    <View style={styles.container}>
      <Input variant="rounded" size="4" placeholder="请输入编号查询" />
      <Text style={{fontSize: 16,margin: 10,color: 'black'}}>筛选</Text>
      <VStack style={{marginLeft: 2,marginRight:10,}}>
        <HStack>

            <Text style={styles.label}>字段</Text>
            <Select style={styles.formcomp} selectValue={filterFiled} w="200" onValueChange={(itemValue) => setFilterFiled(itemValue)}>
              {
                state.tableHead.map((data,index) => {
                  return (
                    <Select.Item key={index} label={data} value={data} />
                  )
                })
              }
            </Select>
          
            <Text style={styles.label}>方式</Text>
            <Select selectValue={filterRule} w="200" onValueChange={(itemValue) => setFliterRule(itemValue)}>
              <Select.Item label="精准查询" value="is"  />
              <Select.Item label="模糊查询" value="like"  />
              <Select.Item label="范围查询" value="in"  />
              {/* <Select.Item label="不在范围查询" value="not_in" /> */}
            </Select>
          
        </HStack>
      </VStack>
      <VStack style={{marginLeft: 2,marginRight:10,}}>
        <HStack>
          
          <Text style={styles.label}>数值</Text>
          {
            filterRule=="in"? 
            (<View style={{flex:1,height: 60,marginTop: 10}}>
              <HStack>
                <Text style={{width: 200}}><FormDatePicker  value={inputvalueRange1} onChange={(e) => setInputvalueRange1(e)} /></Text>
                <Text>—</Text>
                <Text style={{width: 200}}><FormDatePicker value={inputvalueRange2} onChange={(e) => setInputvalueRange2(e)} /></Text>
              </HStack>
            </View>)
            :
            (<Input w="200" value={inputvalue} onChange={(e) => setInputvalue(e.target.text)} onChangeText={(text) => setInputvalue(text)} />)
          }
         
        </HStack>
      </VStack>
      <Pressable style={styles.btn} onPress={()=> fliter()}>
        <Text style={{textAlign: 'center',fontSize:16,color: 'black'}}>查询</Text>
      </Pressable>
      {
        loadingstate ? 
        <ActivityIndicator
          animating={loadingstate}
          style={{alignItems: 'center',justifyContent: 'center',padding: 8, height: 80}}
          size="small" />
          :
        <BasicTable columns={state.tableHead} data={state.tableData} option={{sequence:false, frozen: true}} />
      }
      
      <Fab  renderInPortal={false} shadow={2} size="20" icon={<Ionicons name={'add'} color={'#fafafa'} size={36} />}
         onPress={() => navigation.navigate('addfkd')}
       />
    </View>

  )

}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingTop: StatusBar.currentHeight | 0,
  },
  scrollView: {
    // backgroundColor: 'pink',
    // marginHorizontal: 20,
  },
  table: {
    marginHorizontal: 20,
    marginVertical: 10,
  },
  headerRow: {
    flexDirection: 'row',
    borderBottomWidth: 1,
    borderBottomColor: '#ccc',
    marginTop: 12,
  },
  headerCell: {
    flex: 1,
    fontWeight: 'bold',
    fontSize: 18,
  },
  row: {
    flexDirection: 'row',
    justifyContent: 'center',
    borderBottomWidth: 1,
    borderBottomColor: '#ccc',
    paddingVertical: 12,
  },
  cell: {
    flex: 1,
    paddingVertical: 5,
    paddingHorizontal: 4,
  },
  rowstyle: {
    flexDirection: 'row',
    marginTop: 6,
    marginBottom: 6,
    aliginItems: 'center',
  },
  //
  label: {
    marginLeft: 10,
    marginRight: 10,
    fontSize: 16,
    color: 'black',
    textAlign: 'center',
    textAlignVertical: 'center',
  },
  formcomp: {
    marginRight: 50,
  },
  btn:{
    alignItems: 'center',
    justifyContent: 'center',
    textAlign: 'center',
    width: 80,
    height: 40,
    borderWidth:1,
    borderRadius: 10,
    borderColor: 'rgba(219, 220, 220, 1)',
    margin: 15,
  }
})
export default FkdDetails;